<template>
  <div style="margin-left: 10px;margin-top: 10px">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="分类">
        <el-cascader v-model="categories"  :props="props" />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            v-model="queryParams.brandId"
            placeholder="选择品牌"
            clearable
        >
          <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id">
          </el-option>

        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="initData">搜索</el-button>
        <el-button type="info" @click="initReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="mb-4" style="margin-left: 10px">
    <el-button type="primary" :icon="Plus"  @click="title='添加分类品牌';dialogFormVisible=true">新增</el-button>
    <el-button type="success" :icon="Edit" >修改</el-button>
    <el-button type="danger" :icon="Delete" @click="removeAllButton">删除</el-button>

    <el-dialog v-model="dialogFormVisible" :title="title" width="500">
      <el-form >
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-cascader v-model="categories"  :props="props" placeholder="请选择" />

        </el-form-item>
        <el-form-item label="品牌" :label-width="formLabelWidth">
          <el-select
              v-model="categoryBrand.brandId"
              placeholder="选择品牌"
              clearable
          >
            <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id">
            </el-option></el-select></el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrUpdate">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--品牌数据表格 -->
  <div style="margin-top: 10px">
    <el-table :data="categoryBrands" stripe style="width: 100%" @selection-change="handselectionchange">
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="categoryName" label="分类名称" />
      <el-table-column prop="brandName" label="品牌名称" />
      <el-table-column prop="logo" label="品牌图标" >
        <template #default="scope">
          <img :src="scope.row.logo" style="width: 40px;height: 40px">
        </template>

      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column  label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small"   @click="handleShowEdit(scope.row.id)">修改</el-button>
          <el-button link type="primary" size="small" @click="removeOne(scope.row)">删除</el-button>
        </template>

      </el-table-column>

    </el-table>
    <!--数据分页导航条  pagination表示绑定查询上一页或者下一页分页数据的函数 -->
    <div>
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="initData"
      />

    </div>
  </div>

</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import { reactive } from 'vue'
//引入获取token的工具类
import { getToken } from '@/utils/auth'
import {ElMessage, ElMessageBox} from "element-plus";
import { h } from 'vue'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit
} from '@element-plus/icons-vue'
import {
  listBrand,
  delBrand,
  addBrand,
  updateBrand,
  getBrand,
  listAllBrand,
  slectListByCategoryId
} from '@/api/product/brand.js'

import { listTree} from '@/api/product/category.js'
import {listCategoryBrand,getCategoryBrand,addCategoryBrand,updateCategoryBrand,delCategoryBrand}
  from '@/api/product/categoryBrand.js'
//分页导航条属性
/*const pageNum =ref(1)
const pageSize =ref(3)*/

const total = ref(100)
const queryParams = ref({
  pageNum : 1,
  pageSize :3,
  //搜索表单：采集品牌id的属性
  brandId:null,
  categoryId:null

})
const brands = ref([])
const categoryBrands = ref([])
const categoryBrand = ref({})
const uploadUrl = import.meta.env.VITE_APP_BASE_API+"/file/upload"

const headers = {'Authorization':'Bearer ' +getToken()}

//分类级联器：数据绑定
const categories = ref(null)

const formInline = reactive({
  user: '',
  region: '',
  date: '',
})
const title = ref("添加品牌")

//新增更新品牌对话框: false默认隐藏
const dialogFormVisible  = ref(false)

//表格label宽度属性
const formLabelWidth  = '120'

//收集要新增/更新 的品牌数据的属性
const brand = ref({
  name:'',
  logo:null
})


const props = {
  lazy: true,
  label: 'name',
  value: 'id',
  async lazyLoad(node, resolve) {
    console.log("node:",node)
    let pid;
    if (+node.level===0){
      pid = 0
    }
    else {
      pid = node.data.id
    }
  const{data} = await listTree(pid)
  data.forEach(category=>{
    category.leaf = !category.hasChildren
  })
    resolve(data)
  },
}

const onSubmit = () => {
  console.log('submit!')
}

const handleUpdateValue = async()=>{
  await updateBrand(brand.value)
  ElMessage("修改成功")
}

const handleUpdate = async(row)=>{
  console.log("zaizhe::",row)
    updateCategoryBrand
}

const handleSave=async ()=>{
  await addBrand(brand.value)
  ElMessage("新增成功")
  initData()
}

const handleUploadLogoSuccess = (r)=>{
  if (+r.code ===200){ // +code表示把code转为数字
    brand.value.logo = r.data.url
  }
  else {
    ElMessage.error(r.msg )
  }

}

onMounted(async ()=>{

  //从返回的响应对象中获取rows和total两个属性，使用t接收total属性值
  const {data}=await listAllBrand()
  brands.value = data
  initData();

})

const initData= async()=>{

  if (categories.value && categories.value.length===3){
    queryParams.value.categoryId = categories.value[2]
  }

 const{rows,total:t}= await listCategoryBrand(queryParams.value);
  total.value=t
  categoryBrands.value = rows
}

const initReset=()=>{
  queryParams.value = {
    pageNum: 1,
    pageSize: 3,
    brandId:null,
    categoryId:null,
  }
  categories.value = null

  initData()
}
const removeOne= (row)=>{
  console.log("再这里：",row)
  ElMessageBox.confirm(
      `是否确认删除[${row.brandName}]`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async() => {
    //点击确认删除按钮的回调
    await delCategoryBrand(row.id)

    ElMessage({
      type: 'success',
      message: '删除成功',

    })
    initData()
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}

const handleSaveOrUpdate = async()=>{
  console.log("queryParams.value:",queryParams.value)

  if (!categories.value || categories.value.length !=3 || !categoryBrand.value.brandId){
    ElMessage.warning("请完善所填信息")
    return
  }

  if (categories.value && categories.value.length ===3){

    categoryBrand.value.categoryId = categories.value[2]

    console.log("queryParams.value2:",queryParams.value)
    console.log("categories.value:",categories.value)
    console.log("brands.value:",brands.value)
    console.log("categoryBrand.value:",categoryBrand.value)
  }
  if(categoryBrand.value.id) {
    //更新
   if (updateCategoryBrand(categoryBrand.value)==1) {
     ElMessage.success("修改成功")
   }

    dialogFormVisible.value  = false
    categories.value=null
    initData()
  }
  else {
    //添加
    addCategoryBrand(categoryBrand.value)
    ElMessage.success("添加成功！")
    categories.value=null
    dialogFormVisible.value  = false
    initData()
  }


}
const handleShowEdit= async (id) =>{

      const {data} = await getCategoryBrand(id)
      categoryBrand.value = data;
    console.log("categoryBrand.value:",categoryBrand.value)
  //获取三级id分类集合
  categories.value = data.categoryIdList
  title.value="更新分类品牌"
    dialogFormVisible.value = true

}
const selectBrands = ref([])
const handselectionchange=(newSelection)=>{
  selectBrands.value = newSelection

}
//删除按钮事件函数
const removeAllButton=()=>{
  const selectIds = selectBrands.value.map((brand) => (brand.id))
  if (!selectBrands.value || selectBrands.value.length ===0){
    ElMessage("请选择你要删除的品牌")
    return
  }

  ElMessageBox.confirm(
      "是否确认删除所有选中内容",
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async() => {
    //点击确认删除按钮的回调
    await delBrand(selectIds)

    ElMessage({
      type: 'success',
      message: '删除成功',

    })
    initData()
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })


}
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>